package com.hwadee.caixiang.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hwadee.caixiang.entity.Cart;
import com.hwadee.caixiang.entity.CartItem;
import com.hwadee.caixiang.entity.Product;
import com.hwadee.caixiang.service.ProductService;

@Controller
public class CartController {
	
	private static final Logger logger = LoggerFactory.getLogger(CartController.class);
	
	@Autowired
	private ProductService productService;

	public Cart getCart(HttpSession session) {

		Cart cart = (Cart) session.getAttribute("cart");

		if (cart == null) {

			cart = new Cart();

			session.setAttribute("cart", cart);
		}
		return cart;
	}

	@RequestMapping(value = "/addCart", method = RequestMethod.POST)
	public String addCart(HttpSession session, Integer pid, Integer count) {
		if (pid != null && count != null) {
			logger.info("pid:" + pid);
			logger.info("count:" + count);

			Product product = productService.productfindByPid(pid);

			CartItem cartItem = new CartItem();
			cartItem.setCount(count);
			cartItem.setProduct(product);

			Cart cart = getCart(session);

			cart.addCart(cartItem);
			return "cart";
		} else {
			return "cart";
		}

	}

	@RequestMapping(value = "/clearCart", method = RequestMethod.GET)
	public String clearCart(HttpSession session) {

		Cart cart = getCart(session);
		cart.clearCart();
		return "cart";
	}

	@GetMapping("/removeCart")
	public String removeCart(HttpSession session, Integer pid) {

		Cart cart = getCart(session);
		logger.info("pid:===" + pid);
		if (pid != null) {
			cart.removeCart(pid);
		}
		return "cart";

	}
}
